if (!this.JSON) {
    JSON = {};
}
(function () {

    function f(n) {
        // Format integers to have at least two digits.  
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z';
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions  
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

        // If the string contains no control characters, no quote characters, and no  
        // backslash characters, then we can safely slap some quotes around it.  
        // Otherwise we must also replace the offending characters with safe escape  
        // sequences.  

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

        // Produce a string from holder[key].  

        var i,          // The loop counter.  
            k,          // The member key.  
            v,          // The member value.  
            length,
            mind = gap,
            partial,
            value = holder[key];

        // If the value has a toJSON method, call it to obtain a replacement value.  

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

        // If we were called with a replacer function, then call the replacer to  
        // obtain a replacement value.  

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

        // What happens next depends on the value's type.  

        switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':

                // JSON numbers must be finite. Encode non-finite numbers as null.  

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

                // If the value is a boolean or null, convert it to a string. Note:  
                // typeof null does not produce 'null'. The case is included here in  
                // the remote chance that this gets fixed someday.  

                return String(value);

                // If the type is 'object', we might be dealing with an object or an array or  
                // null.  

            case 'object':

                // Due to a specification blunder in ECMAScript, typeof null is 'object',  
                // so watch out for that case.  

                if (!value) {
                    return 'null';
                }

                // Make an array to hold the partial results of stringifying this object value.  

                gap += indent;
                partial = [];

                // Is the value an array?  

                if (Object.prototype.toString.apply(value) === '[object Array]') {

                    // The value is an array. Stringify every element. Use null as a placeholder  
                    // for non-JSON values.  

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

                    // Join all of the elements together, separated with commas, and wrap them in  
                    // brackets.  

                    v = partial.length === 0 ? '[]' :
                        gap ? '[\n' + gap +
                                partial.join(',\n' + gap) + '\n' +
                                    mind + ']' :
                              '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

                // If the replacer is an array, use it to select the members to be stringified.  

                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {

                    // Otherwise, iterate through all of the keys in the object.  

                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

                // Join all of the member texts together, separated with commas,  
                // and wrap them in braces.  

                v = partial.length === 0 ? '{}' :
                    gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                            mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }

    // If the JSON object does not yet have a stringify method, give it one.  

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

            // The stringify method takes a value and an optional replacer, and an optional  
            // space parameter, and returns a JSON text. The replacer can be a function  
            // that can replace values, or an array of strings that will select the keys.  
            // A default replacer method can be provided. Use of the space parameter can  
            // produce text that is more easily readable.  

            var i;
            gap = '';
            indent = '';

            // If the space parameter is a number, make an indent string containing that  
            // many spaces.  

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

                // If the space parameter is a string, it will be used as the indent string.  

            } else if (typeof space === 'string') {
                indent = space;
            }

            // If there is a replacer, it must be a function or an array.  
            // Otherwise, throw an error.  

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

            // Make a fake root object containing our value under the key of ''.  
            // Return the result of stringifying the value.  

            return str('', { '': value });
        };
    }


    // If the JSON object does not yet have a parse method, give it one.  

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

            // The parse method takes a text and an optional reviver function, and returns  
            // a JavaScript value if the text is a valid JSON text.  

            var j;

            function walk(holder, key) {

                // The walk method is used to recursively walk the resulting structure so  
                // that modifications can be made.  

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


            // Parsing happens in four stages. In the first stage, we replace certain  
            // Unicode characters with escape sequences. JavaScript handles many characters  
            // incorrectly, either silently deleting them, or treating them as line endings.  

            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

            // In the second stage, we run the text against regular expressions that look  
            // for non-JSON patterns. We are especially concerned with '()' and 'new'  
            // because they can cause invocation, and '=' because it can cause mutation.  
            // But just to be safe, we want to reject all unexpected forms.  

            // We split the second stage into 4 regexp operations in order to work around  
            // crippling inefficiencies in IE's and Safari's regexp engines. First we  
            // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we  
            // replace all simple value tokens with ']' characters. Third, we delete all  
            // open brackets that follow a colon or comma or that begin the text. Finally,  
            // we look to see that the remaining characters are only whitespace or ']' or  
            // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.  

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                // In the third stage we use the eval function to compile the text into a  
                // JavaScript structure. The '{' operator is subject to a syntactic ambiguity  
                // in JavaScript: it can begin a block or an object literal. We wrap the text  
                // in parens to eliminate the ambiguity.  

                j = eval('(' + text + ')');

                // In the optional fourth stage, we recursively walk the new structure, passing  
                // each name/value pair to a reviver function for possible transformation.  

                return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
            }

            // If the text is not JSON parseable, then a SyntaxError is thrown.  

            throw new SyntaxError('JSON.parse');
        };
    }
})();

  
$(function () {
    $.browser = $.browser || {};
    var _userAgent = navigator.userAgent.toLowerCase();
    $.browser.mozilla = /firefox/.test(_userAgent);
    $.browser.webkit = /webkit/.test(_userAgent);
    $.browser.opera = /opera/.test(_userAgent);
    $.browser.msie = /msie/.test(_userAgent);


    var userAgent = navigator.userAgent.toLowerCase();//取得浏览器的userAgent字符串
     $.isOpera = userAgent.indexOf("opera") > -1;  //判断是否Opera浏览器
     $.isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("msie") > -1 && !$.isOpera; //判断是否IE浏览器
     $.isFF = userAgent.indexOf("firefox") > -1; //判断是否Firefox浏览器
     $.isSafari = userAgent.indexOf("safari") > -1; //判断是否Safari浏览器
     $.isChrome = userAgent.indexOf("chrome") > -1;

    var _loc = location;
    //字符串格式化
    $.format = function (str, params) {
        if (arguments.length == 1)
            return function () {
                var args = $.makeArray(arguments);
                args.unshift(str);
                return $.format.apply(this, args);
            };
        if (arguments.length > 2 && params.constructor != Array) {
            params = $.makeArray(arguments).slice(1);
        }
        if (params.constructor != Array) {
            params = [params];
        }
        $.each(params, function (i, n) {
            if (str)
                str = str.replace(new RegExp("\\{" + i + "\\}", "g"), n);
        });
        return str;
    };

    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (elt /*, from*/) {
            var len = this.length >>> 0;
            var from = Number(arguments[1]) || 0;
            from = (from < 0)
                 ? Math.ceil(from)
                 : Math.floor(from);
            if (from < 0)
                from += len;
            for (; from < len; from++) {
                if (from in this &&
                    this[from] === elt)
                    return from;
            }
            return -1;
        };
    }


    Date.prototype.format = function (format) {
        var o = {
            "M+": this.getMonth() + 1, //month
            "d+": this.getDate(), //day
            "h+": this.getHours(), //hour
            "m+": this.getMinutes(), //minute
            "s+": this.getSeconds(), //second
            "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
            "S": this.getMilliseconds() //millisecond
        };
        if (/(y+)/.test(format))
            format = format.replace(RegExp.$1,
                (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(format))
                format = format.replace(RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] :
                        ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    };
    $.getArrayIndex = function (arr, value) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == value) {
                return i;
            }
        }
        return -1;
    }
    //cookie操作
    $.cookie = function (name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            var path = options.path ? '; path=' + options.path : '';
            var domain = options.domain ? '; domain=' + options.domain : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };

    $.pageName = function () {

        var _fun = function () {
            var _name = _loc.pathname.toLowerCase().substr(1);
            if (_name.indexOf(".") > 0) {
                _name = _name.substr(0, _name.indexOf("."));
                var _num = _name.lastIndexOf('/');
                if (_num > 0) {
                    _name = _name.substr(_num + 1);
                }
                return _name;
            } else {
                while (_name.length > 1) {
                    var _num = _name.lastIndexOf('/');
                    if (_num != _name.length - 1) {
                        _num = _name.lastIndexOf('/');
                        if (_num > 0) {
                            _name = _name.substr(_num + 1);
                        }
                        var _segs = _name.split('-');
                        if (_segs.length > 1) {
                            return _segs[0];
                        }
                        return _name;
                    } else {
                        _name = _name.substr(0, _num);
                    }
                }

                return _name;
            }
        };
        return _fun() || $.pageDefaultName || '';

    };

    //获取页面参数
    $.urlArg = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = _loc.search.substr(1).match(reg);
        if (r != null)
            return decodeURIComponent(r[2]);

        reg = new RegExp("(^|-)" + name + "-([^-]*)(-|$)", "i");
        r = _loc.pathname.match(reg);
        if (r != null)
            return decodeURIComponent(r[2]);
        return null;
    };

    $.urlArgs = function (d) {
        var name, value, i;
        var str = _loc.href;
        var num = str.indexOf("?");
        str = str.substr(num + 1);
        var arrtmp = str.split("&");
        var data = {};

        for (i = 0; i < arrtmp.length; i++) {
            num = arrtmp[i].indexOf("=");
            if (num > 0) {
                name = arrtmp[i].substring(0, num);
                value = arrtmp[i].substr(num + 1);
                data[name] = value;
            }
        }
        var pathName = _loc.pathname.substr(1);
        if (pathName.indexOf('-') >= 0) {
            if (pathName.lastIndexOf('/') == pathName.length - 1) {
                pathName = pathName.substr(0, pathName.length - 1);
            }
            var n = pathName.lastIndexOf('/');
            if (n > 0) {
                pathName = pathName.substr(n + 1);
            }
            pathName = pathName.substr(pathName.indexOf('-') + 1);
            pathName = pathName.split('-');
            for (var i = 0, l = pathName.length; i < l; i += 2) {
                data[pathName[i]] = pathName[i + 1];
            }
        }
        $.extend(data, d || {});
        return data;
        /* var keys = [];
         $.each(data, function (k, v) { keys.push(k) });
         return { keys: keys.sort(), args: data };*/
    };

    $.dpost = function (url, data, successcallback, errorcallback) {
        //自动获取当前页面
        if (url.indexOf('/') == -1) {
            var _pageName = $.pageName();
            url = _pageName + ".aspx/" + url;
        }

        // shift arguments if data argument was omitted
        if (jQuery.isFunction(data)) {
            callback = data;
            data = undefined;
        }
        var successProxy = function (res) {
            if (res.d && res.d.Table)
                successcallback(res.d.Table);
            else {
                successcallback(res.d);
            }
        };
        var errorProxy = function (v) {
            errorcallback(v);
        };

        //var dogresult =   window.external.GetGuardDog();
        //data.dogresult = dogresult;
        $(".myloading").css("display", "block");

        data = { "jsonstr": JSON.stringify(data) };
        //alert(JSON.stringify(data));
        var ddd = {
            type: "Post",
            url: url,
            data: JSON.stringify(data),
            success: successProxy,
            error: errorProxy,
            dataType: "json",
            contentType: "application/json",
            complete: function () { $(".myloading").css("display", "none"); }
        };
        return $.ajax(ddd);
    };
    $.dpost_async = function (url, data, successcallback, errorcallback) {

        //自动获取当前页面
        if (url.indexOf('/') == -1) {
            var _pageName = $.pageName();
            url = _pageName + ".aspx/" + url;
        }

        // shift arguments if data argument was omitted
        if (jQuery.isFunction(data)) {
            callback = data;
            data = undefined;
        }
        var successProxy = function (res) {
            if (res.d && res.d.Table)
                successcallback(res.d.Table);
            else {
                successcallback(res.d);
            }
        };
        var errorProxy = function () {
            errorcallback();
        };

        //var dogresult = window.external.GetGuardDog();
        //data.dogresult = dogresult;
        $(".myloading").css("display", "block");

        data = { "jsonstr": JSON.stringify(data) };
        //alert(JSON.stringify(data));
        var ddd = {
            type: "Post",
            url: url,
            async: false,
            data: JSON.stringify(data),
            success: successProxy,
            error: errorProxy,
            dataType: "json",
            contentType: "application/json",
            complete: function () { $(".myloading").css("display", "none"); }
        };
        return $.ajax(ddd);
    };

    Math.rand = function (max, min) {
        min = min || 0;
        return Math.round(Math.random() * Math.abs(max - min)) + Math.min(min, max);
    };

    $.padRight = function (str, lenght) {
        str = str + "";
        if (str.length >= lenght)
            return str;
        else
            return $.padRight(str + "0", lenght);
    };
    $.padLeft = function (str, lenght) {
        str = str + "";
        if (str.length >= lenght)
            return str;
        else
            return $.padLeft("0" + str, lenght);
    };
    $.websocket = function (options) {
        var _defaults = {
            domain: top.location.hostname,
            port: "",
            protocol: "",
            autoopen: false
            , onMessage: function (data, event) {
                if (data && data.length >= 31) {
                    var _eventId = data.substr(0, 31);
                    var _event = _events[_eventId];
                    if (_event && _event.cb) {
                        data = data.substr(31);
                        try {
                            data = $.parseJSON(data);
                        } catch (_e) {
                        }
                        _event.cb(data, event, _event);
                    }
                    if (!_event || _event.del !== 0) {
                        delete _events[_eventId];
                    }

                } else {
                    console.error("Message error:长度不够");
                }
            }
        };

        var _events = {};
        var _newLine = "\r\n";
        var _eventNum = 0;
        var emptyEventId = $.padLeft("", 31);
        var _opts = $.extend(_defaults, options);
        var _szServer = "ws://" + _opts.domain + ":" + _opts.port + "/" + _opts.protocol;

        var _timerSocket;
        var _clearTimerSocket = function () {
            if (_timerSocket) {
                clearTimeout(_timerSocket);
                _timerSocket = null;
            }
        };
        var _socketTry = function () {
            if (_opts.autoopen) {
                _clearTimerSocket();
                _timerSocket = setTimeout(function () {
                    _me.start();
                }, 1000);
            }
        };
        var _socket = null;
        var _me = {};
        _me.start = function () {
            _socket = null;
            if (!("WebSocket" in window) && !("MozWebSocket" in window)) {
                return false;
            }
            if (("MozWebSocket" in window)) {
                _socket = new window.MozWebSocket(_szServer);
            } else {
                _socket = new WebSocket(_szServer);
            }
            _socket.binaryType = _opts.binaryType || "arraybuffer";
            _socket.onmessage = function (event) {
                if (_opts.onMessage) {
                    _opts.onMessage(event.data, event, _me);
                }
            };
            _socket.onerror = function (event) {
                console.log("onerror");
                _me.bOpen = false;
                _socketTry();
                if (_opts.onError) {
                    _opts.onError(event, _me);
                }
            };
            _socket.onclose = function (event) {
                console.log("onclose");
                if (_opts.onClose) {
                    _opts.onClose(event, _me);
                }
            };

            _socket.onopen = function (event) {
                _clearTimerSocket();
                _me.bOpen = true;
                if (_opts.onOpen) {
                    _opts.onOpen(event, _me);
                }
            };
        };
        _me.send = function (pData) {
            if (_me.bOpen) {
                try {
                    _socket.send(pData);
                    return true;
                } catch (e) {
                    console.debug(e);
                    return false;
                }
            }
            return false;
        };
        _me.close = function () {
            if (_socket.close() != null) {
                _socket = null;
            }
        };
        //持久化的 
        _me.event = function (event, cb) {
            if ($.isFunction(event)) {
                cb = event;
                event = null;
            }
            var _eventId = event || "longevent";
            if (_eventId && _eventId.length >= 31) {
                _eventId = _eventId.substr(0, 31);
            } else {
                _eventId = $.padRight(_eventId, 31);
            }
            _events[_eventId] = { date: new Date(), cb: cb, eventId: _eventId, del: 0 };
        };
        _me.http = function (opts) {
            var _url = opts.url, _getdata = opts.getdata, _postdata = opts.postdata || opts.data, _cb = opts.cb;

            if (_getdata && $.isFunction(_getdata)) {
                _cb = _getdata;
                _getdata = null;
            }

            if (_postdata && $.isFunction(_postdata)) {
                _cb = _postdata;
                _postdata = null;
            }
            if (_getdata) {
                if ($.isPlainObject(_getdata)) {
                    _getdata = $.param(_getdata);
                }
            } else {
                _getdata = "";
            }
            _url = _url || "";
            var _idx = _url.indexOf('?');
            if (_idx > 0) {
                if (_getdata)
                    _getdata += "&";
                _getdata += _url.substr(_idx + 1);
                _url = _url.substr(0, _idx);
            }
            if ($.isPlainObject(_postdata))
                _postdata = $.toJSON(_postdata);
            var _eventId;
            if (opts.event) {
                //持久化的
                _eventId = opts.event || _url;
                if (_eventId && _eventId.length >= 31) {
                    _eventId = _eventId.substr(0, 31);
                } else {
                    _eventId = $.padRight(_eventId, 31);
                }
            } else {
                if (_cb) {
                    _eventId = $.padLeft(new Date().getTime(), 15) + "_" + $.padLeft(++_eventNum, 15);
                    _events[_eventId] = { date: new Date(), cb: _cb, eventId: _eventId, opts: opts };

                } else {
                    _eventId = emptyEventId;
                }
            }
            var _data = [_eventId, _url, _getdata, _postdata];
            return _me.send(_data.join(_newLine));
        };
        _me.start();
        return _me;
    };

    //$.urlArg=function(name) {
    //    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    //    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    //    if (r != null) return unescape(r[2]); return null; //返回参数值
    //};
 
    $.fn.modal = $.fn.modal || $.noop;
    var _win = $('#winModal').modal({
        keyboard: false,
        show: false,
        backdrop: 'static'
    });

    window.util = {
        showWin: function (title, body, shown) {
            $('.modal-title', _win).html(title);
            $('.modal-body', _win).html(body);
            _win.off("show.bs.modal")
                .off('shown.bs.modal')
                .on("show.bs.modal", function () {
                    if (shown) {
                        shown.call(_win, false);
                    }
                })
                .on('shown.bs.modal', function () {
                    if (shown) {
                        shown.call(_win, true);
                    }
                }).modal('show');
        },
        showFrame: function (title, src, load, shown) {
            var _frame = $("<iframe></iframe>");
            var _loadTimer = setTimeout(function () {
                if (load) {
                    load.call(_frame[0], _win);
                }
            }, 3000);
            _frame.load(function () {
                if (load) {
                    load.call(this, _win);
                }
                clearTimeout(_loadTimer);
            });
            _frame.attr("src", src);
            $(".btnSave", _win).hide();
            this.showWin(title, _frame, shown);
        }
        , hideWin: function () {
            _win.modal('hide');
        }
    };

    window.msg = {
        alert: function (text, modal) {
            this.msgBox(text, modal, 'alert');
        }, error: function (text, modal) {
            if (modal == undefined) {
                modal = true;
            }
            this.msgBox(text, modal, 'error');
        }, warning: function (text, modal) {
            this.msgBox(text, modal, 'warning');
        }, success: function (text, modal) {
            this.msgBox(text, modal, 'success');
        }, info: function (text, modal) {
            this.msgBox(text, modal, 'information');
        }, msgBox: function (text, modal, type) {
            noty({ text: text, type: type, modal: modal, timeout: modal ? false : 3000 });
        }
        , closeAll: function () {
            $.noty.closeAll();
        }
    };
 
    //window.log = console;

    $.fn.formTip = function () {
        return this.each(function () {
            var form = this;
            $("input[name],select[name],textarea[name]", form).off('blur.formTip').on('blur.formTip', function () {
                var ele = $(this);
                var group = ele.parents(".form-group").removeClass("has-error");
                var contion = ele.attr("regex");
                if (contion) {
                    if (!new RegExp(contion).test(ele.val())) {
                        group.addClass("has-error").attr("title", ele.attr("msg") || "不符合输入要求");
                    }
                } contion = ele.attr("eq");
                if (contion) {
                    if (ele.val() != $(contion, form).val()) {
                        group.addClass("has-error").attr("title", ele.attr("eqMsg") || ele.attr("msg") || "不符合输入要求");
                    }
                }

            });

        });
    };

    $.fn.formData = function (data) {
        var form = this;
        if (data) {
            $.each(data, function (key, val) {
                var ele = $("[name='" + key + "']", form);
                if (ele.length === 1) {
                    ele.val(val);
                } else if (ele.length > 1) {
                    $("[name='" + key + "'][value='" + val + "']", form).prop("checked", true);
                }
            });
        } else {
            data = {};
            var flag = false;

            $.each(form.serializeArray(), function (i, item) {
                data[item.name] = item.value;
                var ele = $("[name='" + item.name + "']", form);
                var group = ele.parents(".form-group").removeClass("has-error");
                var regex = ele.attr("regex");
                if (regex) {
                    if (!new RegExp(regex).test(item.value)) {
                        flag = true;
                        group.addClass("has-error").attr("title", ele.attr("msg") || "不符合输入要求");
                    }
                }
            });
            if (flag) {
                msg.warning("输入信息不符合要求,请检测后再试!");
                return false;
            }
        }
        return data;

    };

    (function () {
        'use strict';

        function f(n) {
            // Format integers to have at least two digits.
            return n < 10 ? '0' + n : n;
        }

        if (typeof Date.prototype.toJSON !== 'function') {

            Date.prototype.toJSON = function () {

                return isFinite(this.valueOf())
                    ? this.getUTCFullYear() + '-' +
                        f(this.getUTCMonth() + 1) + '-' +
                        f(this.getUTCDate()) + 'T' +
                        f(this.getUTCHours()) + ':' +
                        f(this.getUTCMinutes()) + ':' +
                        f(this.getUTCSeconds()) + 'Z'
                    : null;
            };

            String.prototype.toJSON =
                Number.prototype.toJSON =
                Boolean.prototype.toJSON = function () {
                    return this.valueOf();
                };
        }

        var cx,
            escapable,
            gap,
            indent,
            meta,
            rep;


        function quote(string) {
            escapable.lastIndex = 0;
            return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string'
                    ? c
                    : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' : '"' + string + '"';
        }


        function str(key, holder) {
            var i,          // The loop counter.
                k,          // The member key.
                v,          // The member value.
                length,
                mind = gap,
                partial,
                value = holder[key];

            if (value && typeof value === 'object' &&
                    typeof value.toJSON === 'function') {
                value = value.toJSON(key);
            }
            if (typeof rep === 'function') {
                value = rep.call(holder, key, value);
            }
            switch (typeof value) {
                case 'string':
                    return quote(value);
                case 'number':
                    return isFinite(value) ? String(value) : 'null';
                case 'boolean':
                case 'null':
                    return String(value);
                case 'object':
                    if (!value) {
                        return 'null';
                    }
                    gap += indent;
                    partial = [];
                    if (Object.prototype.toString.apply(value) === '[object Array]') {
                        length = value.length;
                        for (i = 0; i < length; i += 1) {
                            partial[i] = str(i, value) || 'null';
                        }
                        v = partial.length === 0
                            ? '[]'
                            : gap
                            ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
                            : '[' + partial.join(',') + ']';
                        gap = mind;
                        return v;
                    }
                    if (rep && typeof rep === 'object') {
                        length = rep.length;
                        for (i = 0; i < length; i += 1) {
                            if (typeof rep[i] === 'string') {
                                k = rep[i];
                                v = str(k, value);
                                if (v) {
                                    partial.push(quote(k) + (gap ? ': ' : ':') + v);
                                }
                            }
                        }
                    } else {
                        for (k in value) {
                            if (Object.prototype.hasOwnProperty.call(value, k)) {
                                v = str(k, value);
                                if (v) {
                                    partial.push(quote(k) + (gap ? ': ' : ':') + v);
                                }
                            }
                        }
                    }
                    v = partial.length === 0
                        ? '{}'
                        : gap
                        ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
                        : '{' + partial.join(',') + '}';
                    gap = mind;
                    return v;
            }
        }

        if (typeof JSON.stringify !== 'function') {
            escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
            meta = {    
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"': '\\"',
                '\\': '\\\\'
            };
            JSON.stringify = function (value, replacer, space) {
                var i;
                gap = '';
                indent = '';
                if (typeof space === 'number') {
                    for (i = 0; i < space; i += 1) {
                        indent += ' ';
                    }
                } else if (typeof space === 'string') {
                    indent = space;
                }
                rep = replacer;
                if (replacer && typeof replacer !== 'function' &&
                        (typeof replacer !== 'object' ||
                        typeof replacer.length !== 'number')) {
                    throw new Error('JSON.stringify');
                }
                return str('', { '': value });
            };
        }

        if (typeof JSON.parse !== 'function') {
            cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
            JSON.parse = function (text, reviver) {

                var j;

                function walk(holder, key) {
                    var k, v, value = holder[key];
                    if (value && typeof value === 'object') {
                        for (k in value) {
                            if (Object.prototype.hasOwnProperty.call(value, k)) {
                                v = walk(value, k);
                                if (v !== undefined) {
                                    value[k] = v;
                                } else {
                                    delete value[k];
                                }
                            }
                        }
                    }
                    return reviver.call(holder, key, value);
                }

                text = String(text);
                cx.lastIndex = 0;
                if (cx.test(text)) {
                    text = text.replace(cx, function (a) {
                        return '\\u' +
                            ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                    });
                }

                if (/^[\],:{}\s]*$/
                        .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                            .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                            .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {


                    j = eval('(' + text + ')');

  
                    return typeof reviver === 'function'
                        ? walk({ '': j }, '')
                        : j;
                }

                throw new SyntaxError('JSON.parse');
            };
        }
    }());

    $.toJSON = JSON.stringify;
    $.parseJSON = JSON.parse;

    //获取内容到指定容器
    $.fn.loadc = function (url, cb) {
        var self = this;
        if (self.length == 0) {
            return;
        }
        if (url.indexOf('?') >= 0) {
            url += "&loadcallback=?";
        } else {
            url += "?loadcallback=?";
        }
        self.each(function (i, item) {
            $(".ajaxloading", item).remove();
            $(item).append('<div class="ajaxloading"></div>');
        });
        $.getJSON(url, function (d) {
            $('.ajaxloading', self).remove();
            self.each(function (i, item) {
                if (cb) {
                    d = cb(d, item);
                }
                $(item).append(d);
            });
        });
    };

    $.getCommonDateStr = function (v) {
        v = v.replace(/\-/g, '').replace(/ /g, '').replace(/:/g, '')
        return v;
    };
    $.getCommonDate = function (v) {
        if (v) {
            if (v.length == 8) {

                v = v.substr(0, 4) + '-' + v.substr(4, 2) + '-' + v.substr(6, 2);
            }
            else if (v.length == 14)
                v = v.substr(0, 4) + '-' + v.substr(4, 2) + '-' + v.substr(6, 2) + ' ' +
                    v.substr(8, 2) + ':' + v.substr(10, 2) + ':' + v.substr(12, 2);
        }
        return v;
    };
 
 
    
 
});


 

(function ($) {

    // Add function to jQuery namespace
    $.extend({

        // converts xml documents and xml text to json object
        xml2json: function (xml, extended) {
            if (!xml) return {}; // quick fail

            //### PARSER LIBRARY
            // Core function
            function parseXML(node, simple) {
                if (!node) return null;
                var txt = '', obj = null, att = null;
                var nt = node.nodeType, nn = jsVar(node.localName || node.nodeName);
                var nv = node.text || node.nodeValue || '';
                /*DBG*/ //if(window.console) console.log(['x2j',nn,nt,nv.length+' bytes']);
                if (node.childNodes) {
                    if (node.childNodes.length > 0) {
                        /*DBG*/ //if(window.console) console.log(['x2j',nn,'CHILDREN',node.childNodes]);
                        $.each(node.childNodes, function (n, cn) {
                            var cnt = cn.nodeType, cnn = jsVar(cn.localName || cn.nodeName);
                            var cnv = cn.text || cn.nodeValue || '';
                            /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>a',cnn,cnt,cnv]);
                            if (cnt == 8) {
                                /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>b',cnn,'COMMENT (ignore)']);
                                return; // ignore comment node
                            }
                            else if (cnt == 3 || cnt == 4 || !cnn) {
                                // ignore white-space in between tags
                                if (cnv.match(/^\s+$/)) {
                                    /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>c',cnn,'WHITE-SPACE (ignore)']);
                                    return;
                                };
                                /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>d',cnn,'TEXT']);
                                txt += cnv.replace(/^\s+/, '').replace(/\s+$/, '');
                                // make sure we ditch trailing spaces from markup
                            }
                            else {
                                /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>e',cnn,'OBJECT']);
                                obj = obj || {};
                                if (obj[cnn]) {
                                    /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>f',cnn,'ARRAY']);
                                    if (!obj[cnn].length) obj[cnn] = myArr(obj[cnn]);
                                    obj[cnn][obj[cnn].length] = parseXML(cn, true/* simple */);
                                    obj[cnn].length = obj[cnn].length;
                                }
                                else {
                                    /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>g',cnn,'dig deeper...']);
                                    obj[cnn] = parseXML(cn);
                                };
                            };
                        });
                    };//node.childNodes.length>0
                };//node.childNodes
                if (node.attributes) {
                    if (node.attributes.length > 0) {
                        /*DBG*/ //if(window.console) console.log(['x2j',nn,'ATTRIBUTES',node.attributes])
                        att = {}; obj = obj || {};
                        $.each(node.attributes, function (a, at) {
                            var atn = jsVar(at.name), atv = at.value;
                            att[atn] = atv;
                            if (obj[atn]) {
                                /*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'ARRAY']);
                                if (!obj[atn].length) obj[atn] = myArr(obj[atn]);//[ obj[ atn ] ];
                                obj[atn][obj[atn].length] = atv;
                                obj[atn].length = obj[atn].length;
                            }
                            else {
                                /*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'TEXT']);
                                obj[atn] = atv;
                            };
                        });
                        //obj['attributes'] = att;
                    };//node.attributes.length>0
                };//node.attributes
                if (obj) {
                    obj = $.extend((txt != '' ? new String(txt) : {}),/* {text:txt},*/ obj || {}/*, att || {}*/);
                    txt = (obj.text) ? (typeof (obj.text) == 'object' ? obj.text : [obj.text || '']).concat([txt]) : txt;
                    if (txt) obj.text = txt;
                    txt = '';
                };
                var out = obj || txt;
                //console.log([extended, simple, out]);
                if (extended) {
                    if (txt) out = {};//new String(out);
                    txt = out.text || txt || '';
                    if (txt) out.text = txt;
                    if (!simple) out = myArr(out);
                };
                return out;
            };// parseXML
            // Core Function End
            // Utility functions
            var jsVar = function (s) { return String(s || '').replace(/-/g, "_"); };
            var isNum = function (s) { return (typeof s == "number") || String((s && typeof s == "string") ? s : '').test(/^((-)?([0-9]*)((\.{0,1})([0-9]+))?$)/); };
            var myArr = function (o) {
                if (!o.length) o = [o]; o.length = o.length;
                // here is where you can attach additional functionality, such as searching and sorting...
                return o;
            };
            // Utility functions End
            //### PARSER LIBRARY END

            // Convert plain text to xml
            if (typeof xml == 'string') xml = $.text2xml(xml);

            // Quick fail if not xml (or if this is a node)
            if (!xml.nodeType) return;
            if (xml.nodeType == 3 || xml.nodeType == 4) return xml.nodeValue;

            // Find xml root node
            var root = (xml.nodeType == 9) ? xml.documentElement : xml;

            // Convert xml to json
            var out = parseXML(root, true /* simple */);

            // Clean-up memory
            xml = null; root = null;

            // Send output
            return out;
        },

        // Convert text to XML DOM
        text2xml: function (str) {
            // NOTE: I'd like to use jQuery for this, but jQuery makes all tags uppercase
            //return $(xml)[0];
            var out;
            try {
                var xml = ($.browser.msie) ? new ActiveXObject("Microsoft.XMLDOM") : new DOMParser();
                xml.async = false;
            } catch (e) { throw new Error("XML Parser could not be instantiated") };
            try {
                if ($.browser.msie) out = (xml.loadXML(str)) ? xml : false;
                else out = xml.parseFromString(str, "text/xml");
            } catch (e) { throw new Error("Error parsing XML string") };
            return out;
        }

    }); // extend $
})(jQuery);